package cn.iscorpio;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class PrintABC {

    static String str = "A";

    static Lock lock = new ReentrantLock();
    static Condition condition_a = lock.newCondition();
    static Condition condition_b = lock.newCondition();
    static Condition condition_c = lock.newCondition();

    public static void printA() {
        try {
            lock.lock();
            if (!str.equals("A")) {
                condition_a.await();
            }
            System.out.println(str);
            str = "B";
            condition_b.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void printB() {
        try {
            lock.lock();
            if (!str.equals("B")) {
                condition_b.await();
            }
            System.out.println(str);
            str = "C";
            condition_c.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void printC() {
        try {
            lock.lock();
            if (!str.equals("C")) {
                condition_c.await();
            }
            System.out.println(str);
            str = "A";
            condition_a.signal();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {

        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                PrintABC.printA();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                PrintABC.printB();
            }
        }).start();
        new Thread(() -> {
            for (int i = 0; i < 10; i++) {
                PrintABC.printC();
            }
        }).start();

    }
}
